package br.com.simora.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

import br.com.simora.arquivo.ArquivoDAO;
import br.com.simora.execucao.LogErroCapturaDAO;
import br.com.simora.radio.Radio;

@Named("streamWorldHelper")
public class StreamTheWorldHelper {
	private static Logger logger = Logger.getLogger(StreamTheWorldHelper.class);
	@Inject private LogErroCapturaDAO logErroCapturaDAO;
	@Inject private ArquivoDAO arquivoDAO;
	
	/**
	 * Este método:
	 * 1 - cria um arquivo com nome timestamp
	 * 2 - acessa a url da rádio e grava o streaming no arquivo
	 * 3 - retorna 
	 * */
	public String capturaStream(Radio radio){
		File f = arquivoDAO.criaArquivoTimestamp(radio.getNome());
		try{
            URLConnection conn = new URL(radio.getUrl()).openConnection();
            InputStream is = conn.getInputStream();
            OutputStream outstream = new FileOutputStream(f);
            byte[] buffer = new byte[4096];
            int len;
            long t = System.currentTimeMillis();
            while ((len = is.read(buffer)) > 0 && System.currentTimeMillis() - t <= 5000) {
                outstream.write(buffer, 0, len);
            }
            outstream.close();
        }
        catch(Exception e){
        	logErroCapturaDAO.gravaErro(radio, e.getMessage(), new Date());
        	logger.debug(e.getMessage());
        	arquivoDAO.deletaArquivo(f);
        	return null;
        }
		return f.getAbsolutePath();
	}

}